package com.getpebble.android.framework.protocol.inbound;

import com.getpebble.android.bluetooth.protocol.ProtocolMessage;
import com.getpebble.android.framework.protocol.EndpointId;

public abstract class PblInboundMessage {

    public class InvalidMessageSizeException extends RuntimeException {
        public InvalidMessageSizeException(String message) {
            super(message);
        }
    }

    abstract EndpointId getId();

    protected abstract int getMinSize();

    public PblInboundMessage(ProtocolMessage message) {
        if (message == null) {
            throw new IllegalArgumentException("'message' cannot be null!");
        }
        checkEndpointId(message);
        checkBufferSize(message);
    }

    protected void checkEndpointId(ProtocolMessage message) {
        if (!EndpointId.fromCode(message.getEndpointId()).equals(getId())) {
            throw new IllegalArgumentException("ProtocolMessage's endpointId must be " + getId().name());
        }
    }

    protected void checkBufferSize(ProtocolMessage message) {
        if (message.getDataSize() > 2048) {
            throw new InvalidMessageSizeException("The buffer must be smaller than 2048");
        } else if (message.getDataSize() < getMinSize()) {
            throw new InvalidMessageSizeException("The buffer must be larger than " + getMinSize());
        }
    }
}
